import pyttsx3
import keyboard
import time
import threading

class SpeechManager:
    def __init__(self, cfg=None):
        cfg = cfg or {}
        self.rate = cfg.get('speech_rate', 250)
        self.volume = cfg.get('speech_volume', 1.0)
        self.ctrl_count = cfg.get('speech_ctrl_count', 3)
        self.interval = cfg.get('speech_ctrl_interval', 0.3)
        self.stop_key = cfg.get('speech_stop_key', 'ctrl')
        self._stop_flag = False

    def _stop_on_key(self, engine):
        presses = 0
        last_time = None
        while not self._stop_flag:
            if keyboard.is_pressed(self.stop_key):
                now = time.time()
                if last_time is None or now - last_time <= self.interval:
                    presses += 1
                else:
                    presses = 1
                last_time = now
                while keyboard.is_pressed(self.stop_key):
                    time.sleep(0.05)
                if presses == self.ctrl_count:
                    engine.stop()
                    break
            time.sleep(0.01)

    def speak(self, text):
        self._stop_flag = False
        engine = pyttsx3.init()
        engine.setProperty('rate', self.rate)
        engine.setProperty('volume', self.volume)
        t = threading.Thread(target=self._stop_on_key, args=(engine,), daemon=True)
        t.start()
        try:
            engine.say(text)
            engine.runAndWait()
        finally:
            self._stop_flag = True
            del engine

